package com.smart.community.region.service.impl;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.Objects;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.smart.community.commons.cache.DataScopeInfo;
import com.smart.community.commons.utils.SecurityUtils;
import com.smart.community.commons.exception.BusinessException;
import com.smart.community.commons.utils.StringUtils;
import com.smart.community.feign.property.service.DataScopeFeign;
import com.smart.community.region.dto.HouseholdDTO;
import com.smart.community.region.dto.HouseholdQueryDTO;
import com.smart.community.region.dto.HouseholdUpdateDTO;
import com.smart.community.region.entity.Building;
import com.smart.community.region.entity.Household;
import com.smart.community.region.entity.PropertyHouseType;
import com.smart.community.region.entity.Unit;
import com.smart.community.region.mapper.BuildingMapper;
import com.smart.community.region.mapper.HouseholdMapper;
import com.smart.community.region.service.CommunityCacheService;
import com.smart.community.region.service.IBuildingService;
import com.smart.community.region.service.ICommunityService;
import com.smart.community.region.service.IHouseholdService;
import com.smart.community.region.service.IPropertyHouseTypeService;
import com.smart.community.region.service.IUnitService;
import com.smart.community.region.service.RegionCacheService;
import com.smart.community.region.vo.CommunityVO;
import com.smart.community.region.vo.HouseholdVO;
import com.smart.community.region.vo.HouseholdDeleteImpactVO;
import com.smart.community.feign.region.dto.HouseholdInfoDTO;
import com.smart.community.region.entity.Owner;
import com.smart.community.region.entity.OwnerHousehold;
import com.smart.community.region.entity.Resident;
import com.smart.community.region.entity.ResidentHousehold;
import com.smart.community.region.mapper.OwnerMapper;
import com.smart.community.region.mapper.OwnerHouseholdMapper;
import com.smart.community.region.mapper.ResidentMapper;
import com.smart.community.region.mapper.ResidentHouseholdMapper;

import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;

/**
 * 住户管理服务实现类
 *
 * @author Wu.Liang
 * @since 2024-12-21
 */
@Slf4j
@Service
public class HouseholdServiceImpl extends ServiceImpl<HouseholdMapper, Household> implements IHouseholdService {

    @Autowired
    private IUnitService unitService;

    @Autowired
    private BuildingMapper buildingMapper;

    @Autowired
    private RegionCacheService regionCacheService;

    @Autowired
    private DataScopeFeign dataScopeFeign;

    @Autowired
    private OwnerMapper ownerMapper;

    @Autowired
    private OwnerHouseholdMapper ownerHouseholdMapper;

    @Autowired
    private ResidentMapper residentMapper;

    @Autowired
    private ResidentHouseholdMapper residentHouseholdMapper;

    @Autowired
    private IPropertyHouseTypeService propertyHouseTypeService;

    @Autowired
    private ICommunityService communityService;

    @Autowired
    private IBuildingService buildingService;

    @Autowired
    private CommunityCacheService communityCacheService;

    @Override
    // 注意：移除@Cacheable注解，避免IPage<Household>复杂对象序列化/反序列化时的ClassCastException问题
    // 复杂对象（如IPage、PageResult、自定义VO等）在Redis缓存中容易出现类型转换错误
    // 遵循《Java后端SpringBoot代码开发规范.md》的缓存使用规范
    public IPage<Household> getHouseholdPage(HouseholdQueryDTO queryDTO) {
        long startTime = System.currentTimeMillis();
        log.info("分页查询住户列表，查询条件：{}", queryDTO);
        
        try {
            // 构建查询条件
            LambdaQueryWrapper<Household> queryWrapper = new LambdaQueryWrapper<>();
        
        // 房户编码模糊查询
        if (StringUtils.isNotBlank(queryDTO.getHouseholdCode())) {
            queryWrapper.like(Household::getHouseholdCode, queryDTO.getHouseholdCode());
        }
        
        // 社区ID查询
        if (queryDTO.getCommunityId() != null) {
            queryWrapper.eq(Household::getCommunityId, queryDTO.getCommunityId());
        }
        
        // 楼栋ID查询
        if (queryDTO.getBuildingId() != null) {
            queryWrapper.eq(Household::getBuildingId, queryDTO.getBuildingId());
        }
        
        // 单元ID查询
        if (queryDTO.getUnitId() != null) {
            queryWrapper.eq(Household::getUnitId, queryDTO.getUnitId());
        }
        
        // 楼层号查询
        if (queryDTO.getFloorNumber() != null) {
            queryWrapper.eq(Household::getFloorNumber, queryDTO.getFloorNumber());
        }
        
        // 房间号模糊查询
        if (StringUtils.isNotBlank(queryDTO.getRoomNumber())) {
            queryWrapper.like(Household::getRoomNumber, queryDTO.getRoomNumber());
        }
        
        // 房间类型查询
        if (queryDTO.getRoomType() != null) {
            queryWrapper.eq(Household::getRoomType, queryDTO.getRoomType());
        }
        
        // 状态查询
        if (queryDTO.getStatus() != null) {
            queryWrapper.eq(Household::getStatus, queryDTO.getStatus());
        }
        
        // 面积范围查询
        if (queryDTO.getAreaMin() != null) {
            queryWrapper.ge(Household::getArea, queryDTO.getAreaMin());
        }
        if (queryDTO.getAreaMax() != null) {
            queryWrapper.le(Household::getArea, queryDTO.getAreaMax());
        }
        
        // 产权类型查询
        if (queryDTO.getPropertyType() != null) {
            queryWrapper.eq(Household::getPropertyType, queryDTO.getPropertyType());
        }
        
        // 关键词搜索（房屋号、房户编码）
        if (StringUtils.isNotBlank(queryDTO.getKeyword())) {
            queryWrapper.and(wrapper -> wrapper
                .like(Household::getRoomNumber, queryDTO.getKeyword())
                .or().like(Household::getHouseholdCode, queryDTO.getKeyword())
            );
        }
        
        // 创建时间范围查询
        if (StringUtils.isNotBlank(queryDTO.getCreateTimeStart())) {
            queryWrapper.ge(Household::getCreateTime, queryDTO.getCreateTimeStart() + " 00:00:00");
        }
        if (StringUtils.isNotBlank(queryDTO.getCreateTimeEnd())) {
            queryWrapper.le(Household::getCreateTime, queryDTO.getCreateTimeEnd() + " 23:59:59");
        }
        
        // 排序
        queryWrapper.orderByDesc(Household::getUpdateTime);
        
        // 应用数据权限过滤
        applyDataPermissionFilter(queryWrapper);
        
        // 分页查询
        Page<Household> page = new Page<>(queryDTO.getCurrent(), queryDTO.getSize());
        IPage<Household> result = this.page(page, queryWrapper);
        
            // 填充关联的社区、楼栋、单元信息
            if (result != null && result.getRecords() != null && !result.getRecords().isEmpty()) {
                fillRelatedInfo(result.getRecords());
            }
            
            long endTime = System.currentTimeMillis();
            log.info("分页查询住户列表成功，耗时：{}ms，记录数：{}", endTime - startTime, result.getTotal());
            return result;
            
        } catch (Exception e) {
            long endTime = System.currentTimeMillis();
            log.error("分页查询住户列表失败，耗时：{}ms，查询条件：{}", endTime - startTime, queryDTO, e);
            return createEmptyPage(queryDTO);
        }
    }

    @Override
    @Cacheable(value = "household:detail", key = "#householdId", unless = "#result == null")
    public Household getHouseholdDetail(Long householdId) {
        long startTime = System.currentTimeMillis();
        log.info("根据ID查询住户详情，住户ID：{}", householdId);
        
        try {
            if (householdId == null) {
                log.warn("住户ID为空，返回null");
                return null;
            }
            
            Household household = this.getById(householdId);
            if (household == null) {
                log.warn("住户不存在，住户ID：{}", householdId);
                return null;
            }
            
            // 填充关联的社区、楼栋、单元信息
            fillRelatedInfo(Collections.singletonList(household));
            
            long endTime = System.currentTimeMillis();
            log.info("根据ID查询住户详情成功，耗时：{}ms，住户ID：{}", endTime - startTime, householdId);
            return household;
            
        } catch (Exception e) {
            long endTime = System.currentTimeMillis();
            log.error("根据ID查询住户详情失败，耗时：{}ms，住户ID：{}", endTime - startTime, householdId, e);
            return null;
        }
    }

    @Override
    @Cacheable(value = "household:code", key = "#householdCode", unless = "#result == null")
    public Household getHouseholdByCode(String householdCode) {
        long startTime = System.currentTimeMillis();
        log.info("根据编码查询住户，住户编码：{}", householdCode);
        
        try {
            if (StringUtils.isBlank(householdCode)) {
                log.warn("住户编码为空，返回null");
                return null;
            }
            
            Household household = baseMapper.selectByHouseholdCode(householdCode);
            if (household == null) {
                log.warn("住户不存在，住户编码：{}", householdCode);
                return null;
            }
            
            long endTime = System.currentTimeMillis();
            log.info("根据编码查询住户成功，耗时：{}ms，住户编码：{}", endTime - startTime, householdCode);
            return household;
            
        } catch (Exception e) {
            long endTime = System.currentTimeMillis();
            log.error("根据编码查询住户失败，耗时：{}ms，住户编码：{}", endTime - startTime, householdCode, e);
            return null;
        }
    }

	@Override
	@GlobalTransactional(rollbackFor = Exception.class)
	@CacheEvict(value = {
		"household:page", "household:detail", "household:code", "household:feign:ids",
		"household:basicStats", "household:countByCommunity", "household:countByUnit",
		"household:byBuilding", "household:byCommunity", "household:byUnitId",
		"household:groupedByUnit", "household:byCommunityIds", "household:idsByUnitIds",
		"household:userIdsByHouseholdIds", "household:idsByUnitId", "household:idsByCommunityIds",
		"household:feign:batch", "household:owners", "household:familyMembers", "household:tenants",
		"datascope:householdIds", "datascope:householdPermission",
		"address"
	}, allEntries = true)
	public boolean createHousehold(HouseholdDTO householdDTO) {
        log.info("新增住户，住户信息：{}", householdDTO);
        
        // 参数校验
        validateHouseholdDTO(householdDTO);
        
        // 检查住户编码是否已存在
        if (baseMapper.existsByHouseholdCode(householdDTO.getHouseholdCode(), null)) {
            throw new BusinessException("住户编码已存在");
        }
        
        // 检查单元是否存在
        if (householdDTO.getUnitId() != null) {
            Unit unit = unitService.getById(householdDTO.getUnitId());
            if (unit == null) {
                throw new BusinessException("单元不存在");
            }
        }
        
        // 构建住户实体
        Household household = new Household();
        BeanUtils.copyProperties(householdDTO, household);
        
        // 设置创建信息
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {
            throw new BusinessException("获取当前用户信息失败");
        }
        household.setCreateBy(userId);
        household.setCreateTime(LocalDateTime.now());
        household.setUpdateBy(userId);
        household.setUpdateTime(LocalDateTime.now());
        household.setDeleted(0);
        
        // 保存住户
        boolean result = this.save(household);
        if (result) {
            log.info("新增住户成功，住户ID：{}", household.getId());
            // 清除缓存
            clearHouseholdCache(household.getId());
        }
        
        return result;
    }

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    @CacheEvict(value = {
        "household:page", "household:detail", "household:code", 
        "household:byBuilding", "household:byCommunity", "household:byUnitId",
        "household:groupedByUnit", "household:byCommunityIds", "household:idsByUnitIds",
        "household:userIdsByHouseholdIds", "household:idsByUnitId", "household:idsByCommunityIds",
        "household:feign:ids", "address:byHouseholdId", "address:byHouseholdIds",
        "owner:household", "owner_household:owner", "owner_household:vos", 
        "owner_household:household", "owner_household:household_vos", "owner_household:household_ids",
        "owner_household:owner_household", "owner_household:primary", "owner_household:primary_households",
        "owner_household:exists", "owner_household:vo"
    }, allEntries = true)
    public boolean updateHousehold(HouseholdDTO householdDTO) {
        log.info("更新住户，住户信息：{}", householdDTO);
        
        // 参数校验
        validateHouseholdDTO(householdDTO);
        
        // 检查住户是否存在
        Household existingHousehold = this.getById(householdDTO.getId());
        if (existingHousehold == null) {
            throw new BusinessException("住户不存在");
        }
        
        // 注意：更新时不检查住户编码唯一性，因为住户编码是不可编辑的字段
        
        // 检查单元是否存在（如果传递了单元ID）
        if (householdDTO.getUnitId() != null) {
            Unit unit = unitService.getById(householdDTO.getUnitId());
            if (unit == null) {
                throw new BusinessException("单元不存在");
            }
        }
        
        // 更新住户信息 - 跳过不可编辑的字段
        // 不可编辑的字段：householdCode, communityId, buildingId, unitId, floorNumber
        existingHousehold.setRoomNumber(householdDTO.getRoomNumber());
        existingHousehold.setRoomType(householdDTO.getRoomType());
        existingHousehold.setArea(householdDTO.getArea());
        existingHousehold.setUsableArea(householdDTO.getUsableArea());
        existingHousehold.setOrientation(householdDTO.getOrientation());
        existingHousehold.setPropertyType(householdDTO.getPropertyType());
        existingHousehold.setPropertyCertificate(householdDTO.getPropertyCertificate());
        existingHousehold.setPurchaseDate(householdDTO.getPurchaseDate());
        existingHousehold.setPropertyFeeRate(householdDTO.getPropertyFeeRate());
        existingHousehold.setStatus(householdDTO.getStatus());
        existingHousehold.setSortOrder(householdDTO.getSortOrder());
        existingHousehold.setDescription(householdDTO.getDescription());
        
        // 设置更新信息
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {
            throw new BusinessException("获取当前用户信息失败");
        }
        existingHousehold.setUpdateBy(userId);
        existingHousehold.setUpdateTime(LocalDateTime.now());
        
        // 乐观锁处理：确保版本号正确设置
        if (existingHousehold.getVersion() == null) {
            existingHousehold.setVersion(1);
        }
        
        // 保存更新
        boolean result = this.updateById(existingHousehold);
        if (result) {
            log.info("更新住户成功，住户ID：{}", existingHousehold.getId());
            // 清除缓存
            clearHouseholdCache(existingHousehold.getId());
        }
        
        return result;
    }

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    @CacheEvict(value = {
        "household:page", "household:detail", "household:code", 
        "household:byBuilding", "household:byCommunity", "household:byUnitId",
        "household:groupedByUnit", "household:byCommunityIds", "household:idsByUnitIds",
        "household:userIdsByHouseholdIds", "household:idsByUnitId", "household:idsByCommunityIds",
        "household:feign:ids", "address:byHouseholdId", "address:byHouseholdIds",
        "owner:household", "owner_household:owner", "owner_household:vos", 
        "owner_household:household", "owner_household:household_vos", "owner_household:household_ids",
        "owner_household:owner_household", "owner_household:primary", "owner_household:primary_households",
        "owner_household:exists", "owner_household:vo"
    }, allEntries = true)
    public boolean updateHousehold(HouseholdUpdateDTO householdUpdateDTO) {
        log.info("更新住户（使用更新DTO），住户信息：{}", householdUpdateDTO);
        
        try {
            // 检查住户是否存在
            Household existingHousehold = this.getById(householdUpdateDTO.getId());
            if (existingHousehold == null) {
                throw new BusinessException("住户不存在");
            }
            
            // 更新住户信息 - 只更新可编辑的字段
            existingHousehold.setRoomNumber(householdUpdateDTO.getRoomNumber());
            existingHousehold.setRoomType(householdUpdateDTO.getRoomType());
            existingHousehold.setArea(householdUpdateDTO.getArea());
            existingHousehold.setUsableArea(householdUpdateDTO.getUsableArea());
            existingHousehold.setOrientation(householdUpdateDTO.getOrientation());
            existingHousehold.setPropertyType(householdUpdateDTO.getPropertyType());
            existingHousehold.setPropertyCertificate(householdUpdateDTO.getPropertyCertificate());
            existingHousehold.setPurchaseDate(householdUpdateDTO.getPurchaseDate());
            existingHousehold.setPropertyFeeRate(householdUpdateDTO.getPropertyFeeRate());
            existingHousehold.setStatus(householdUpdateDTO.getStatus());
            existingHousehold.setSortOrder(householdUpdateDTO.getSortOrder());
            existingHousehold.setDescription(householdUpdateDTO.getDescription());
            
            // 设置更新信息
            Long userId = SecurityUtils.getCurrentUserId();
            if (userId == null) {
                throw new BusinessException("获取当前用户信息失败");
            }
            existingHousehold.setUpdateBy(userId);
            existingHousehold.setUpdateTime(LocalDateTime.now());
            
            // 乐观锁处理：确保版本号正确设置
            if (existingHousehold.getVersion() == null) {
                existingHousehold.setVersion(1);
            }
            
            // 保存更新
            boolean result = this.updateById(existingHousehold);
            if (result) {
                log.info("更新住户成功，住户ID：{}", existingHousehold.getId());
                // 清除缓存
                clearHouseholdCache(existingHousehold.getId());
            }
            
            return result;
            
        } catch (Exception e) {
            log.error("更新住户失败", e);
            throw new BusinessException("更新住户失败：" + e.getMessage());
        }
    }

	@Override
	@GlobalTransactional(rollbackFor = Exception.class)
	@CacheEvict(value = {
		"household:page", "household:detail", "household:code", "household:feign:ids",
		"household:basicStats", "household:countByCommunity", "household:countByUnit",
		"household:byBuilding", "household:byCommunity", "household:byUnitId",
		"household:groupedByUnit", "household:byCommunityIds", "household:idsByUnitIds",
		"household:userIdsByHouseholdIds", "household:idsByUnitId", "household:idsByCommunityIds",
		"household:feign:batch", "household:owners", "household:familyMembers", "household:tenants",
		"datascope:householdIds", "datascope:householdPermission",
		"address"
	}, allEntries = true)
	public boolean deleteHousehold(Long householdId) {
        log.info("删除住户，住户ID：{}", householdId);
        
        try {
            // 检查住户是否存在
            Household household = this.getById(householdId);
            if (household == null) {
                throw new BusinessException("住户不存在");
            }
            
            // 逻辑删除
            household.setDeleted(1);
            household.setUpdateTime(LocalDateTime.now());
            
            // 乐观锁处理：确保版本号正确设置
            if (household.getVersion() == null) {
                household.setVersion(1);
            }
            
            boolean result = this.updateById(household);
            if (result) {
                log.info("删除住户成功，住户ID：{}", householdId);
                // 清除缓存
                clearHouseholdCache(householdId);
            }
            
            return result;
            
        } catch (Exception e) {
            log.error("删除住户失败，住户ID：{}", householdId, e);
            throw new BusinessException("删除住户失败：" + e.getMessage());
        }
    }

	@Override
	@GlobalTransactional(rollbackFor = Exception.class)
	@CacheEvict(value = {
		"household:page", "household:detail", "household:code", "household:feign:ids",
		"household:basicStats", "household:countByCommunity", "household:countByUnit",
		"household:byBuilding", "household:byCommunity", "household:byUnitId",
		"household:groupedByUnit", "household:byCommunityIds", "household:idsByUnitIds",
		"household:userIdsByHouseholdIds", "household:idsByUnitId", "household:idsByCommunityIds",
		"household:feign:batch", "household:owners", "household:familyMembers", "household:tenants",
		"datascope:householdIds", "datascope:householdPermission",
		"address"
	}, allEntries = true)
	public boolean batchDeleteHouseholds(List<Long> householdIds) {
        log.info("批量删除住户，住户ID列表：{}", householdIds);
        
        try {
            if (householdIds == null || householdIds.isEmpty()) {
                throw new BusinessException("住户ID列表不能为空");
            }
            
            // 批量逻辑删除
            List<Household> households = this.listByIds(householdIds);
            if (households.size() != householdIds.size()) {
                throw new BusinessException("部分住户不存在");
            }
            
            for (Household household : households) {
                household.setDeleted(1);
                household.setUpdateTime(LocalDateTime.now());
                
                // 乐观锁处理：确保版本号正确设置
                if (household.getVersion() == null) {
                    household.setVersion(1);
                }
            }
            
            boolean result = this.updateBatchById(households);
            if (result) {
                log.info("批量删除住户成功，住户ID列表：{}", householdIds);
                // 清除缓存
                for (Long householdId : householdIds) {
                    clearHouseholdCache(householdId);
                }
            }
            
            return result;
            
        } catch (Exception e) {
            log.error("批量删除住户失败", e);
            throw new BusinessException("批量删除住户失败：" + e.getMessage());
        }
    }

    @Override
    @Cacheable(value = "household:byBuilding", key = "#buildingId", unless = "#result == null || #result.isEmpty()")
    public List<Household> getHouseholdsByBuilding(Long buildingId) throws Exception {
        log.info("根据楼栋ID查询住户列表，楼栋ID：{}", buildingId);
        
        LambdaQueryWrapper<Household> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Household::getBuildingId, buildingId)
                .eq(Household::getDeleted, 0)
                .orderByAsc(Household::getFloorNumber, Household::getRoomNumber);
        
        return this.list(queryWrapper);
    }

    @Override
    @Cacheable(value = "household:byCommunity", key = "#communityId", unless = "#result == null || #result.isEmpty()")
    public List<Household> getHouseholdsByCommunity(Long communityId) throws Exception {
        log.info("根据社区ID查询住户列表，社区ID：{}", communityId);
        
        return baseMapper.selectByCommunityId(communityId);
    }

    @Override
    @Cacheable(value = "household:byUnitId", key = "#unitId", unless = "#result == null || #result.isEmpty()")
    public List<Household> getHouseholdByUnitId(Long unitId) throws Exception {
        log.info("根据单元ID查询住户列表，单元ID：{}", unitId);
        
        LambdaQueryWrapper<Household> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Household::getUnitId, unitId)
                .eq(Household::getDeleted, 0)
                .orderByAsc(Household::getFloorNumber, Household::getRoomNumber);
        
        return this.list(queryWrapper);
    }

    @Override
    @Cacheable(value = "household:groupedByUnit", key = "#communityIds.hashCode() + ':' + #unitIds.hashCode() + ':' + #status", unless = "#result == null || #result.isEmpty()")
    public List<Household> getHouseholdsGroupedByUnit(List<Long> communityIds, List<Long> unitIds, Integer status) throws Exception {
        log.info("根据社区ID批量查询住户，支持按单元分组返回和状态过滤，社区ID列表：{}，单元ID列表：{}，状态：{}", communityIds, unitIds, status);
        
        return baseMapper.selectGroupedByUnit(communityIds, unitIds, status);
    }

    @Override
    @Cacheable(value = "household:byCommunityIds", key = "#communityIds.hashCode() + ':' + #unitIds.hashCode() + ':' + #status", unless = "#result == null || #result.isEmpty()")
    public List<Household> getHouseholdsByCommunityIds(List<Long> communityIds, List<Long> unitIds, Integer status) throws Exception {
        log.info("根据社区ID批量查询住户，社区ID列表：{}，单元ID列表：{}，状态：{}", communityIds, unitIds, status);
        
        return baseMapper.selectByCommunityIds(communityIds, unitIds, status);
    }

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    @CacheEvict(value = {
        "household:page", "household:detail", "household:code", 
        "household:byBuilding", "household:byCommunity", "household:byUnitId",
        "household:groupedByUnit", "household:byCommunityIds", "household:idsByUnitIds",
        "household:userIdsByHouseholdIds", "household:idsByUnitId", "household:idsByCommunityIds",
        "household:feign:ids", "address:byHouseholdId", "address:byHouseholdIds",
        "owner:household", "owner_household:owner", "owner_household:vos", 
        "owner_household:household", "owner_household:household_vos", "owner_household:household_ids",
        "owner_household:owner_household", "owner_household:primary", "owner_household:primary_households",
        "owner_household:exists", "owner_household:vo"
    }, allEntries = true)
    public boolean updateHouseholdStatus(Long householdId, Integer status) {
        log.info("更新住户状态，住户ID：{}，状态：{}", householdId, status);
        
        try {
            Household household = this.getById(householdId);
            if (household == null) {
                throw new BusinessException("住户不存在");
            }
            
            household.setStatus(status);
            household.setUpdateTime(LocalDateTime.now());
            
            // 乐观锁处理：确保版本号正确设置
            if (household.getVersion() == null) {
                household.setVersion(1);
            }
            
            boolean result = this.updateById(household);
            if (result) {
                log.info("更新住户状态成功，住户ID：{}，状态：{}", householdId, status);
                clearHouseholdCache(householdId);
            }
            
            return result;
            
        } catch (Exception e) {
            log.error("更新住户状态失败，住户ID：{}，状态：{}", householdId, status, e);
            throw new BusinessException("更新住户状态失败：" + e.getMessage());
        }
    }

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    @CacheEvict(value = {
        "household:page", "household:detail", "household:code", 
        "household:byBuilding", "household:byCommunity", "household:byUnitId",
        "household:groupedByUnit", "household:byCommunityIds", "household:idsByUnitIds",
        "household:userIdsByHouseholdIds", "household:idsByUnitId", "household:idsByCommunityIds",
        "household:feign:ids", "address:byHouseholdId", "address:byHouseholdIds",
        "owner:household", "owner_household:owner", "owner_household:vos", 
        "owner_household:household", "owner_household:household_vos", "owner_household:household_ids",
        "owner_household:owner_household", "owner_household:primary", "owner_household:primary_households",
        "owner_household:exists", "owner_household:vo"
    }, allEntries = true)
    public boolean batchUpdateHouseholdStatus(List<Long> householdIds, Integer status) {
        log.info("批量更新住户状态，住户ID列表：{}，状态：{}", householdIds, status);
        
        try {
            if (householdIds == null || householdIds.isEmpty()) {
                throw new BusinessException("住户ID列表不能为空");
            }
            
            List<Household> households = this.listByIds(householdIds);
            if (households.size() != householdIds.size()) {
                throw new BusinessException("部分住户不存在");
            }
            
            for (Household household : households) {
                household.setStatus(status);
                household.setUpdateTime(LocalDateTime.now());
                
                // 乐观锁处理：确保版本号正确设置
                if (household.getVersion() == null) {
                    household.setVersion(1);
                }
            }
            
            boolean result = this.updateBatchById(households);
            if (result) {
                log.info("批量更新住户状态成功，住户ID列表：{}，状态：{}", householdIds, status);
                for (Long householdId : householdIds) {
                    clearHouseholdCache(householdId);
                }
            }
            
            return result;
            
        } catch (Exception e) {
            log.error("批量更新住户状态失败", e);
            throw new BusinessException("批量更新住户状态失败：" + e.getMessage());
        }
    }

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    @CacheEvict(value = {
        "household:page", "household:detail", "household:code", 
        "household:byBuilding", "household:byCommunity", "household:byUnitId",
        "household:groupedByUnit", "household:byCommunityIds", "household:idsByUnitIds",
        "household:userIdsByHouseholdIds", "household:idsByUnitId", "household:idsByCommunityIds",
        "household:feign:ids", "address:byHouseholdId", "address:byHouseholdIds",
        "owner:household", "owner_household:owner", "owner_household:vos", 
        "owner_household:household", "owner_household:household_vos", "owner_household:household_ids",
        "owner_household:owner_household", "owner_household:primary", "owner_household:primary_households",
        "owner_household:exists", "owner_household:vo"
    }, allEntries = true)
    public boolean batchUpdateHouseholdHouseType(List<Long> householdIds, Long houseTypeId) {
        log.info("批量更新住户户型，住户ID列表：{}，户型ID：{}", householdIds, houseTypeId);
        
        try {
            // 参数校验
            if (householdIds == null || householdIds.isEmpty()) {
                throw new BusinessException("住户ID列表不能为空");
            }
            
            if (houseTypeId == null) {
                throw new BusinessException("户型ID不能为空");
            }
            
            // 获取户型配置信息
            PropertyHouseType houseType = propertyHouseTypeService.getById(houseTypeId);
            if (houseType == null) {
                throw new BusinessException("户型配置不存在");
            }
            
            // 使用原生SQL批量更新，避免乐观锁问题
            int updateCount = baseMapper.batchUpdateHouseTypeWithFields(
                householdIds, 
                houseTypeId, 
                houseType.getHouseTypeName(),
                houseType.getTotalArea(),
                houseType.getUsableArea(),
                houseType.getOrientation(),
                getRoomTypeByBedroomCount(houseType.getBedroomCount())
            );
            
            if (updateCount > 0) {
                log.info("批量更新住户户型成功，更新数量：{}，住户ID列表：{}，户型ID：{}", updateCount, householdIds, houseTypeId);
                
                // 清除缓存
                for (Long householdId : householdIds) {
                    clearHouseholdCache(householdId);
                }
                
                return true;
            } else {
                log.warn("批量更新住户户型失败，没有记录被更新，住户ID列表：{}，户型ID：{}", householdIds, houseTypeId);
                return false;
            }
            
        } catch (Exception e) {
            log.error("批量更新住户户型失败", e);
            throw new BusinessException("批量更新住户户型失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据卧室数量获取房间类型
     * @param bedroomCount 卧室数量
     * @return 房间类型：1-一室，2-两室，3-三室，4-四室及以上
     */
    private Integer getRoomTypeByBedroomCount(Integer bedroomCount) {
        if (bedroomCount == null) {
            return 1; // 默认一室
        }
        
        if (bedroomCount == 1) {
            return 1; // 一室
        } else if (bedroomCount == 2) {
            return 2; // 两室
        } else if (bedroomCount == 3) {
            return 3; // 三室
        } else if (bedroomCount >= 4) {
            return 4; // 四室及以上
        }
        
        return 1; // 默认一室
    }

    @Override
    public Object getHouseholdStats(Long householdId) {
        log.info("获取住户统计信息，住户ID：{}", householdId);
        
        try {
            Household household = this.getById(householdId);
            if (household == null) {
                throw new BusinessException("住户不存在");
            }
            
            // 构建统计信息
            Map<String, Object> stats = new HashMap<>();
            stats.put("householdId", householdId);
            stats.put("roomNumber", household.getRoomNumber());
            stats.put("area", household.getArea());
            stats.put("roomType", household.getRoomType());
            stats.put("status", household.getStatus());
            
            return stats;
            
        } catch (Exception e) {
            log.error("获取住户统计信息失败，住户ID：{}", householdId, e);
            throw new BusinessException("获取住户统计信息失败：" + e.getMessage());
        }
    }

    @Override
    public Object getCommunityOccupancyStats(Long communityId) {
        log.info("获取社区入住率统计，社区ID：{}", communityId);
        
        try {
            // 统计总户数
            Long totalHouseholds = baseMapper.countByCommunityId(communityId);
            
            // 统计已入住户数
            Long occupiedHouseholds = baseMapper.countOccupiedByCommunityId(communityId);
            
            // 计算入住率
            double occupancyRate = totalHouseholds > 0 ? (double) occupiedHouseholds / totalHouseholds * 100 : 0;
            
            // 构建统计信息
            Map<String, Object> stats = new HashMap<>();
            stats.put("communityId", communityId);
            stats.put("totalHouseholds", totalHouseholds);
            stats.put("occupiedHouseholds", occupiedHouseholds);
            stats.put("occupancyRate", occupancyRate);
            
            return stats;
            
        } catch (Exception e) {
            log.error("获取社区入住率统计失败，社区ID：{}", communityId, e);
            throw new BusinessException("获取社区入住率统计失败：" + e.getMessage());
        }
    }

    @Override
    public boolean checkHouseholdCodeUnique(String householdCode, Long excludeHouseholdId) {
        log.info("检查住户编码唯一性，住户编码：{}，排除住户ID：{}", householdCode, excludeHouseholdId);
        
        try {
            return !baseMapper.existsByHouseholdCode(householdCode, excludeHouseholdId);
            
        } catch (Exception e) {
            log.error("检查住户编码唯一性失败", e);
            throw new BusinessException("检查住户编码唯一性失败：" + e.getMessage());
        }
    }

    @Override
    public Long countHouseholds(Long unitId) {
        log.info("统计住户数量，单元ID：{}", unitId);
        
        try {
            LambdaQueryWrapper<Household> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Household::getDeleted, 0);
            
            if (unitId != null) {
                queryWrapper.eq(Household::getUnitId, unitId);
            }
            
            return Long.valueOf(this.count(queryWrapper));
            
        } catch (Exception e) {
            log.error("统计住户数量失败，单元ID：{}", unitId, e);
            throw new BusinessException("统计住户数量失败：" + e.getMessage());
        }
    }

    @Override
    public void clearHouseholdCache(Long householdId) {
        log.info("清除住户缓存，住户ID：{}", householdId);
        
        try {
            // 清除住户详情缓存
            regionCacheService.clearRegionCache(householdId);
            
            // 清除住户列表缓存
            regionCacheService.clearAllRegionCache();
            
        } catch (Exception e) {
            log.error("清除住户缓存失败，住户ID：{}", householdId, e);
        }
    }

    @Override
    public void clearAllHouseholdCache() {
        log.info("清除所有住户缓存");
        
        try {
            // 清除所有住户相关缓存
            regionCacheService.clearAllRegionCache();
            
        } catch (Exception e) {
            log.error("清除所有住户缓存失败", e);
        }
    }

    // ==================== 私有方法 ====================

    /**
     * 创建空的分页结果
     */
    private IPage<Household> createEmptyPage(HouseholdQueryDTO queryDTO) {
        Page<Household> emptyPage = new Page<>(queryDTO.getCurrent(), queryDTO.getSize(), 0L);
        emptyPage.setRecords(Collections.emptyList());
        return emptyPage;
    }

    private HouseholdVO convertToVO(Household household) {
        if (household == null) {
            return null;
        }
        
        HouseholdVO householdVO = new HouseholdVO();
        BeanUtils.copyProperties(household, householdVO);
        
        // 设置关联信息
        if (household.getUnitId() != null) {
            try {
                Unit unit = unitService.getById(household.getUnitId());
                if (unit != null) {
                    householdVO.setUnitName(unit.getUnitName());
                    
                    // 设置楼栋信息
                    if (unit.getBuildingId() != null) {
                        Building building = buildingMapper.selectById(unit.getBuildingId());
                        if (building != null) {
                            householdVO.setBuildingId(building.getId());
                            householdVO.setBuildingName(building.getBuildingName());
                            
                            // 设置社区信息
                            if (building.getCommunityId() != null) {
                                try {
                                    // 通过CommunityService获取社区信息
                                    CommunityVO communityVO = communityService.getCommunityById(building.getCommunityId());
                                    if (communityVO != null) {
                                        householdVO.setCommunityId(communityVO.getId());
                                        householdVO.setCommunityName(communityVO.getCommunityName());
                                    }
                                } catch (Exception e) {
                                    log.warn("获取社区信息失败，社区ID：{}", building.getCommunityId(), e);
                                }
                            }
                        }
                    }
                }
            } catch (Exception e) {
                log.warn("获取关联信息失败，住户ID：{}", household.getId(), e);
                householdVO.setUnitName("未知单元");
                householdVO.setBuildingName("未知楼栋");
                householdVO.setCommunityName("未知社区");
            }
        }
        
        return householdVO;
    }

    /**
     * 批量转换为VO对象（优化版本，使用批量缓存查询）
     */
    public List<HouseholdVO> convertToVOList(List<Household> households) {
        if (households == null || households.isEmpty()) {
            return new ArrayList<>();
        }

        // 收集所有单元ID
        List<Long> unitIds = households.stream()
                .map(Household::getUnitId)
                .filter(Objects::nonNull)
                .distinct()
                .collect(Collectors.toList());

        // 批量获取单元信息
        Map<Long, Unit> unitMap = new HashMap<>();
        if (!unitIds.isEmpty()) {
            try {
                List<Unit> units = unitService.listByIds(unitIds);
                unitMap = units.stream()
                        .collect(Collectors.toMap(Unit::getId, unit -> unit));
            } catch (Exception e) {
                log.warn("批量获取单元信息失败", e);
            }
        }

        // 收集所有楼栋ID
        List<Long> buildingIds = unitMap.values().stream()
                .map(Unit::getBuildingId)
                .filter(Objects::nonNull)
                .distinct()
                .collect(Collectors.toList());

        // 批量获取楼栋信息
        Map<Long, Building> buildingMap = new HashMap<>();
        if (!buildingIds.isEmpty()) {
            try {
                // 通过BuildingService批量获取楼栋信息
                List<Building> buildings = buildingService.listByIds(buildingIds);
                buildingMap = buildings.stream()
                        .collect(Collectors.toMap(Building::getId, building -> building));
            } catch (Exception e) {
                log.warn("批量获取楼栋信息失败", e);
            }
        }

        // 收集所有社区ID
        List<Long> communityIds = buildingMap.values().stream()
                .map(Building::getCommunityId)
                .filter(Objects::nonNull)
                .distinct()
                .collect(Collectors.toList());

        // 批量获取社区信息
        Map<Long, CommunityVO> communityMap = new HashMap<>();
        if (!communityIds.isEmpty()) {
            try {
                // 通过CommunityCacheService批量获取社区信息
                communityMap = communityCacheService.getCommunitiesByIds(communityIds);
            } catch (Exception e) {
                log.warn("批量获取社区信息失败", e);
            }
        }

        // 转换为VO
        final Map<Long, Unit> finalUnitMap = unitMap;
        final Map<Long, Building> finalBuildingMap = buildingMap;
        final Map<Long, CommunityVO> finalCommunityMap = communityMap;
        return households.stream().map(household -> {
            HouseholdVO vo = new HouseholdVO();
            BeanUtils.copyProperties(household, vo);
            
            // 填充关联信息
            if (household.getUnitId() != null) {
                Unit unit = finalUnitMap.get(household.getUnitId());
                if (unit != null) {
                    vo.setUnitName(unit.getUnitName());
                    
                    // 填充楼栋信息
                    if (unit.getBuildingId() != null) {
                        Building building = finalBuildingMap.get(unit.getBuildingId());
                        if (building != null) {
                            vo.setBuildingId(building.getId());
                            vo.setBuildingName(building.getBuildingName());
                            
                            // 填充社区信息
                            if (building.getCommunityId() != null) {
                                CommunityVO community = finalCommunityMap.get(building.getCommunityId());
                                if (community != null) {
                                    vo.setCommunityId(community.getId());
                                    vo.setCommunityName(community.getCommunityName());
                                }
                            }
                        }
                    }
                } else {
                    vo.setUnitName("未知单元");
                    vo.setBuildingName("未知楼栋");
                    vo.setCommunityName("未知社区");
                }
            }
            
            return vo;
        }).collect(Collectors.toList());
    }

    private void validateHouseholdDTO(HouseholdDTO householdDTO) {
        if (householdDTO == null) {
            throw new BusinessException("住户信息不能为空");
        }
        
        // 新增时校验所有必填字段
        if (householdDTO.getId() == null) {
            // 新增模式
            if (StringUtils.isBlank(householdDTO.getHouseholdCode())) {
                throw new BusinessException("住户编码不能为空");
            }
            
            if (householdDTO.getUnitId() == null) {
                throw new BusinessException("所属单元不能为空");
            }
            
            if (StringUtils.isBlank(householdDTO.getRoomNumber())) {
                throw new BusinessException("房间号不能为空");
            }
            
            if (householdDTO.getFloorNumber() == null || householdDTO.getFloorNumber() <= 0) {
                throw new BusinessException("楼层号必须大于0");
            }
        } else {
            // 更新模式 - 只校验可编辑字段
            if (StringUtils.isBlank(householdDTO.getRoomNumber())) {
                throw new BusinessException("房间号不能为空");
            }
        }
    }

    // ==================== 数据权限业务接口实现 ====================

    @Override
    @Cacheable(value = "household:idsByUnitIds", key = "#unitIds.hashCode()", unless = "#result == null || #result.isEmpty()")
    public List<Long> getHouseholdIdsByUnitIds(List<Long> unitIds) {
        log.info("根据单元ID集合获取房户ID集合，单元数量：{}", unitIds != null ? unitIds.size() : 0);
        try {
            if (unitIds == null || unitIds.isEmpty()) {
                return new ArrayList<>();
            }
            
            // 查询指定单元下的所有房户ID
            LambdaQueryWrapper<Household> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.select(Household::getId);
            queryWrapper.in(Household::getUnitId, unitIds);
            queryWrapper.eq(Household::getDeleted, 0);
            
            List<Household> households = this.list(queryWrapper);
            List<Long> householdIds = households.stream()
                    .map(Household::getId)
                    .collect(Collectors.toList());
            
            log.info("根据单元ID集合获取房户ID集合成功，单元数量：{}，房户数量：{}", unitIds.size(), householdIds.size());
            return householdIds;
        } catch (Exception e) {
            log.error("根据单元ID集合获取房户ID集合失败，单元IDs：{}", unitIds, e);
            return new ArrayList<>();
        }
    }

    @Override
    @Cacheable(value = "household:userIdsByHouseholdIds", key = "#householdIds.hashCode()", unless = "#result == null || #result.isEmpty()")
    public List<Long> getUserIdsByHouseholdIds(List<Long> householdIds) {
        log.info("根据房户ID集合获取用户ID集合，房户数量：{}", householdIds != null ? householdIds.size() : 0);
        try {
            if (householdIds == null || householdIds.isEmpty()) {
                return new ArrayList<>();
            }
            
            // 实现根据房户ID获取用户ID的逻辑
            // 这里需要调用住户服务获取用户ID
            // 这里需要调用用户服务或查询用户房户关联表
            // 暂时返回空列表，等待用户服务提供相应接口
            
            log.info("根据房户ID集合获取用户ID集合成功，房户数量：{}，用户数量：0", householdIds.size());
            return new ArrayList<>();
        } catch (Exception e) {
            log.error("根据房户ID集合获取用户ID集合失败，房户IDs：{}", householdIds, e);
            return new ArrayList<>();
        }
    }

    @Override
    @Cacheable(value = "household:idsByUnitId", key = "#unitId", unless = "#result == null || #result.isEmpty()")
    public List<Long> getHouseholdIdsByUnitId(Long unitId) {
        log.info("根据单元ID获取房户ID列表，单元ID：{}", unitId);
        try {
            if (unitId == null) {
                return new ArrayList<>();
            }
            
            // 查询指定单元下的所有房户ID
            LambdaQueryWrapper<Household> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.select(Household::getId);
            queryWrapper.eq(Household::getUnitId, unitId);
            queryWrapper.eq(Household::getDeleted, 0);
            
            List<Household> households = this.list(queryWrapper);
            List<Long> householdIds = households.stream()
                    .map(Household::getId)
                    .collect(Collectors.toList());
            
            log.info("根据单元ID获取房户ID列表成功，单元ID：{}，房户数量：{}", unitId, householdIds.size());
            return householdIds;
        } catch (Exception e) {
            log.error("根据单元ID获取房户ID列表失败，单元ID：{}", unitId, e);
            return new ArrayList<>();
        }
    }

    /**
     * 应用数据权限过滤
     * 根据《智慧社区微服务架构总览.md》权威标准实现
     * 1. 如果是超级管理员，可以查看所有数据
     * 2. 如果不是超级管理员，但有关联物业公司，那么就取关联的物业公司，再取物业公司的社区集合，再取社区集合范围内的楼栋集合，再取楼栋集合范围内的单元集合，再取单元集合范围内的房户集合，分页展示
     */
    private void applyDataPermissionFilter(LambdaQueryWrapper<Household> queryWrapper) {
        try {
            // 获取当前用户信息
            DataScopeInfo dataScopeInfo = dataScopeFeign.getUserDataScope(SecurityUtils.getCurrentUserId());
            
            // 超级管理员跳过数据权限过滤
            if (dataScopeInfo.isSuperAdmin()) {
                return;
            }
            
            // 检查用户是否有关联物业公司
            if (!dataScopeInfo.isPropertyCompanyUser()) {
                queryWrapper.eq(Household::getId, -1L); // 返回空结果
                return;
            }
            
            // 获取用户可访问的社区ID集合
            List<Long> communityIds = dataScopeInfo.getCommunityIds();
            if (communityIds.isEmpty()) {
                queryWrapper.eq(Household::getId, -1L); // 返回空结果
                return;
            }
            
            // 获取用户可访问的楼栋ID集合
            List<Long> buildingIds = getBuildingIdsByCommunityIds(communityIds);
            if (buildingIds.isEmpty()) {
                queryWrapper.eq(Household::getId, -1L); // 返回空结果
                return;
            }
            
            // 获取用户可访问的单元ID集合
            List<Long> unitIds = unitService.getUnitIdsByBuildingIds(buildingIds);
            if (unitIds.isEmpty()) {
                queryWrapper.eq(Household::getId, -1L); // 返回空结果
                return;
            }
            
            // 应用单元权限过滤
            queryWrapper.in(Household::getUnitId, unitIds);
        } catch (Exception e) {
            log.error("应用数据权限过滤失败", e);
            queryWrapper.eq(Household::getId, -1L); // 异常时返回空结果
        }
    }

    /**
     * 根据社区ID集合获取楼栋ID列表
     * @param communityIds 社区ID集合
     * @return 楼栋ID列表
     */
    private List<Long> getBuildingIdsByCommunityIds(List<Long> communityIds) {
        log.info("根据社区ID集合获取楼栋ID列表，社区数量：{}", communityIds != null ? communityIds.size() : 0);
        try {
            if (communityIds == null || communityIds.isEmpty()) {
                return new ArrayList<>();
            }
            
            // 查询指定社区下的所有楼栋ID
            LambdaQueryWrapper<Building> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.select(Building::getId);
            queryWrapper.in(Building::getCommunityId, communityIds);
            queryWrapper.eq(Building::getDeleted, 0);
            
            List<Building> buildings = buildingMapper.selectList(queryWrapper);
            List<Long> buildingIds = buildings.stream()
                    .map(Building::getId)
                    .collect(Collectors.toList());
            
            log.info("根据社区ID集合获取楼栋ID列表成功，社区数量：{}，楼栋数量：{}", communityIds.size(), buildingIds.size());
            return buildingIds;
        } catch (Exception e) {
            log.error("根据社区ID集合获取楼栋ID列表失败，社区IDs：{}", communityIds, e);
            return new ArrayList<>();
        }
    }

    @Override
    @Cacheable(value = "household:idsByCommunityIds", key = "#communityIds.hashCode()", unless = "#result == null || #result.isEmpty()")
    public List<Long> getHouseholdIdsByCommunityIds(List<Long> communityIds) throws Exception {
        log.info("根据社区ID集合获取房户ID集合，社区数量：{}", communityIds != null ? communityIds.size() : 0);
        
        try {
            if (communityIds == null || communityIds.isEmpty()) {
                return new ArrayList<>();
            }
            
            // 1. 根据社区ID获取楼栋ID列表
            List<Long> buildingIds = getBuildingIdsByCommunityIds(communityIds);
            if (buildingIds.isEmpty()) {
                log.info("社区下无楼栋数据，返回空房户ID列表");
                return new ArrayList<>();
            }
            
            // 2. 根据楼栋ID获取单元ID列表
            List<Long> unitIds = unitService.getUnitIdsByBuildingIds(buildingIds);
            if (unitIds.isEmpty()) {
                log.info("楼栋下无单元数据，返回空房户ID列表");
                return new ArrayList<>();
            }
            
            // 3. 根据单元ID获取房户ID列表
            List<Long> householdIds = getHouseholdIdsByUnitIds(unitIds);
            
            log.info("根据社区ID集合获取房户ID集合成功，社区数量：{}，楼栋数量：{}，单元数量：{}，房户数量：{}", 
                    communityIds.size(), buildingIds.size(), unitIds.size(), householdIds.size());
            
            return householdIds;
            
        } catch (Exception e) {
            log.error("根据社区ID集合获取房户ID集合失败，社区IDs：{}", communityIds, e);
            return new ArrayList<>();
        }
    }

    // ==================== 房户生成方法实现 ====================

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public int generateHouseholdsForUnit(Unit unit, Long buildingId, Integer floorCount, Integer unitsPerFloor) {
        log.info("为单元批量生成房户记录，单元ID：{}，楼栋ID：{}，楼层数：{}，每层户数：{}", unit.getId(), buildingId, floorCount, unitsPerFloor);
        
        try {
            if (unit.getId() == null || buildingId == null || floorCount == null || unitsPerFloor == null) {
                throw new BusinessException("参数不能为空");
            }
            
            if (floorCount <= 0 || unitsPerFloor <= 0) {
                throw new BusinessException("楼层数和每层户数必须大于0");
            }
            
            List<Household> households = new ArrayList<>();
            Long currentUserId = SecurityUtils.getCurrentUserId();
            
            // 二维数组循环创建房户对象
            // 第一层循环是楼栋的楼层数(从1开始)
            // 第二层循环是每层户数(从1开始)
            for (int floor = 1; floor <= floorCount; floor++) {
                for (int unitIndex = 1; unitIndex <= unitsPerFloor; unitIndex++) {
                    Household household = new Household();
                    
                    // 房间号命名规则：{楼层号}{每层户数序号(需两位，不到两位前面补0)}
                    String roomNumber = String.format("%d%02d", floor, unitIndex);
                    
                    // 房户编码默认跟房间号一致
                    String householdCode = roomNumber;

                    household.setHouseholdCode(householdCode);
                    household.setCommunityId(unit.getCommunityId());
                    household.setBuildingId(buildingId);
                    household.setUnitId(unit.getId());
                    household.setFloorNumber(floor);
                    household.setRoomNumber(roomNumber);                    
                    // 每户的面积（默认是单元面积除以每层户数）
                    double ha = unit.getArea().doubleValue() / unitsPerFloor;
                    household.setArea(BigDecimal.valueOf(ha));
                    
                    // 其他字段默认值设置
                    household.setRoomType(1); // 默认一室
                    household.setStatus(1); // 默认已入住状态
                    household.setCreateBy(currentUserId);
                    household.setUpdateBy(currentUserId);
                    household.setCreateTime(LocalDateTime.now());
                    household.setUpdateTime(LocalDateTime.now());
                    household.setDeleted(0);
                    
                    households.add(household);
                }
            }
            
            // 批量保存房户记录
            if (!households.isEmpty()) {
                this.saveBatch(households);
                log.info("单元房户生成成功，单元ID：{}，生成房户数量：{}", unit.getId(), households.size());
                return households.size();
            }
            
            return 0;
            
        } catch (Exception e) {
            log.error("为单元批量生成房户记录失败，单元ID：{}", unit.getId(), e);
            throw new BusinessException("生成房户记录失败：" + e.getMessage());
        }
    }

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public int updateHouseholdsForUnit(Long unitId, Long buildingId, Integer floorCount, Integer unitsPerFloor) {
        log.info("更新单元的房户记录，单元ID：{}，楼栋ID：{}，楼层数：{}，每层户数：{}", unitId, buildingId, floorCount, unitsPerFloor);
        
        try {
            if (unitId == null || buildingId == null || floorCount == null || unitsPerFloor == null) {
                throw new BusinessException("参数不能为空");
            }
            
            if (floorCount <= 0 || unitsPerFloor <= 0) {
                throw new BusinessException("楼层数和每层户数必须大于0");
            }
            
            // 检查单元是否存在
            Unit unit = unitService.getById(unitId);
            if (unit == null) {
                throw new BusinessException("单元不存在");
            }
            
            Long currentUserId = SecurityUtils.getCurrentUserId();
            int updatedCount = 0;
            
            // 二维数组循环更新房户信息
            // 第一层循环是楼栋的楼层数(从1开始)
            // 第二层循环是每层户数(从1开始)
            for (int floor = 1; floor <= floorCount; floor++) {
                for (int unitIndex = 1; unitIndex <= unitsPerFloor; unitIndex++) {
                    // 房间号命名规则：{楼层号}{每层户数序号(需两位，不到两位前面补0)}
                    String roomNumber = String.format("%d%02d", floor, unitIndex);
                    
                    // 根据building_id, unit_id, room_number这三个字段为条件，查询房户信息
                    LambdaQueryWrapper<Household> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(Household::getBuildingId, buildingId);
                    queryWrapper.eq(Household::getUnitId, unitId);
                    queryWrapper.eq(Household::getRoomNumber, roomNumber);
                    queryWrapper.eq(Household::getDeleted, 0);
                    
                    Household existingHousehold = this.getOne(queryWrapper);
                    
                    if (existingHousehold == null) {
                        // 如果以上根据building_id, unit_id, room_number这三个字段没有查到房户信息，那么我们新增此条房户信息
                        Household newHousehold = new Household();
                        
                        // 房户编码默认跟房间号一致
                        String householdCode = roomNumber;
                        
                        newHousehold.setHouseholdCode(householdCode);
                        newHousehold.setCommunityId(unit.getCommunityId());
                        newHousehold.setBuildingId(buildingId);
                        newHousehold.setUnitId(unitId);
                        newHousehold.setFloorNumber(floor);
                        newHousehold.setRoomNumber(roomNumber);
                        
                        // 其他字段默认值设置
                        newHousehold.setRoomType(1); // 默认一室
                        newHousehold.setStatus(1); // 默认已入住状态
                        newHousehold.setCreateBy(currentUserId);
                        newHousehold.setUpdateBy(currentUserId);
                        newHousehold.setCreateTime(LocalDateTime.now());
                        newHousehold.setUpdateTime(LocalDateTime.now());
                        newHousehold.setDeleted(0);
                        
                        this.save(newHousehold);
                        updatedCount++;
                        log.debug("新增房户记录，单元ID：{}，房间号：{}", unitId, roomNumber);
                    } else {
                        // 如果以上根据building_id, unit_id, room_number这三个字段查到房户信息已存在，那么就 continue
                        log.debug("房户记录已存在，跳过更新，单元ID：{}，房间号：{}", unitId, roomNumber);
                        continue;
                    }
                }
            }
            
            log.info("单元房户更新成功，单元ID：{}，更新房户数量：{}", unitId, updatedCount);
            return updatedCount;
            
        } catch (Exception e) {
            log.error("更新单元的房户记录失败，单元ID：{}", unitId, e);
            throw new BusinessException("更新房户记录失败：" + e.getMessage());
        }
    }

    /**
     * 填充房户关联的社区、楼栋、单元信息
     */
    private void fillRelatedInfo(List<Household> households) {
        try {
            if (households == null || households.isEmpty()) {
                return;
            }
            
            // 收集所有的楼栋ID和单元ID
            Set<Long> buildingIds = new HashSet<>();
            Set<Long> unitIds = new HashSet<>();
            
            for (Household household : households) {
                if (household.getBuildingId() != null) {
                    buildingIds.add(household.getBuildingId());
                }
                if (household.getUnitId() != null) {
                    unitIds.add(household.getUnitId());
                }
            }
            
            // 批量获取楼栋信息
            Map<Long, Building> buildingMap = new HashMap<>();
            if (!buildingIds.isEmpty()) {
                try {
                    // 通过BuildingService批量获取楼栋信息
                    List<Building> buildings = buildingService.listByIds(new ArrayList<>(buildingIds));
                    buildingMap = buildings.stream()
                            .collect(Collectors.toMap(Building::getId, building -> building));
                } catch (Exception e) {
                    log.warn("批量获取楼栋信息失败", e);
                }
            }
            
            // 批量获取单元信息
            Map<Long, Unit> unitMap = new HashMap<>();
            if (!unitIds.isEmpty()) {
                try {
                    List<Unit> units = unitService.listByIds(new ArrayList<>(unitIds));
                    unitMap = units.stream()
                            .collect(Collectors.toMap(Unit::getId, unit -> unit));
                } catch (Exception e) {
                    log.warn("批量获取单元信息失败", e);
                }
            }
            
            // 收集所有的社区ID
            Set<Long> communityIds = new HashSet<>();
            for (Building building : buildingMap.values()) {
                if (building.getCommunityId() != null) {
                    communityIds.add(building.getCommunityId());
                }
            }
            
            // 批量获取社区信息
            Map<Long, CommunityVO> communityMap = new HashMap<>();
            if (!communityIds.isEmpty()) {
                try {
                    // 通过CommunityCacheService批量获取社区信息
                    communityMap = communityCacheService.getCommunitiesByIds(new ArrayList<>(communityIds));
                } catch (Exception e) {
                    log.warn("批量获取社区信息失败", e);
                }
            }
            
            // 填充房户的关联信息
            for (Household household : households) {
                // 填充楼栋信息
                if (household.getBuildingId() != null && buildingMap.containsKey(household.getBuildingId())) {
                    Building building = buildingMap.get(household.getBuildingId());
                    household.setBuildingName(building.getBuildingName());
                    household.setBuildingCode(building.getBuildingNo());
                    
                    // 填充社区信息
                    if (building.getCommunityId() != null && communityMap.containsKey(building.getCommunityId())) {
                        CommunityVO community = communityMap.get(building.getCommunityId());
                        household.setCommunityName(community.getCommunityName());
                        household.setCommunityCode(community.getCommunityCode());
                    }
                }
                
                // 填充单元信息
                if (household.getUnitId() != null && unitMap.containsKey(household.getUnitId())) {
                    Unit unit = unitMap.get(household.getUnitId());
                    household.setUnitName(unit.getUnitName());
                    household.setUnitCode(unit.getUnitCode());
                }
            }
            
            log.debug("填充房户关联信息完成，房户数量：{}", households.size());
            
        } catch (Exception e) {
            log.error("填充房户关联信息失败", e);
        }
    }

    @Override
    public String deleteHouseholdWithRelations(Long householdId, Long currentUserId) throws BusinessException {
        log.info("删除房户（带关联处理），房户ID：{}，用户ID：{}", householdId, currentUserId);
        
        try {
            // 验证删除权限
            validateDeletePermission(householdId, currentUserId);
            
            // 检查删除影响
            HouseholdDeleteImpactVO impact = checkDeleteImpact(householdId);
            if (impact.getTotalRelatedCount() > 0) {
                throw new BusinessException("该房户存在关联数据，无法删除：" + impact.getSummary());
            }
            
            // 执行删除
            boolean success = this.removeById(householdId);
            if (!success) {
                throw new BusinessException("删除房户失败");
            }
            
            // 清除缓存
            clearHouseholdCache(householdId);
            
            log.info("房户删除成功，房户ID：{}", householdId);
            return "删除成功";
            
        } catch (Exception e) {
            log.error("删除房户失败，房户ID：{}", householdId, e);
            throw new BusinessException("删除房户失败：" + e.getMessage());
        }
    }

    @Override
    public String batchDeleteHouseholdsWithRelations(List<Long> householdIds, Long currentUserId) throws BusinessException {
        log.info("批量删除房户（带关联处理），房户ID列表：{}，用户ID：{}", householdIds, currentUserId);
        
        try {
            if (householdIds == null || householdIds.isEmpty()) {
                throw new BusinessException("房户ID列表不能为空");
            }
            
            List<String> successList = new ArrayList<>();
            List<String> failList = new ArrayList<>();
            
            for (Long householdId : householdIds) {
                try {
                    String result = deleteHouseholdWithRelations(householdId, currentUserId);
                    successList.add("房户ID " + householdId + ": " + result);
                } catch (Exception e) {
                    failList.add("房户ID " + householdId + ": " + e.getMessage());
                }
            }
            
            StringBuilder result = new StringBuilder();
            result.append("批量删除完成。成功：").append(successList.size()).append("个，失败：").append(failList.size()).append("个。");
            
            if (!successList.isEmpty()) {
                result.append("成功列表：").append(String.join("; ", successList));
            }
            if (!failList.isEmpty()) {
                result.append("失败列表：").append(String.join("; ", failList));
            }
            
            log.info("批量删除房户完成，成功：{}个，失败：{}个", successList.size(), failList.size());
            return result.toString();
            
        } catch (Exception e) {
            log.error("批量删除房户失败", e);
            throw new BusinessException("批量删除房户失败：" + e.getMessage());
        }
    }

    @Override
    public HouseholdDeleteImpactVO checkDeleteImpact(Long householdId) {
        log.info("检查房户删除影响，房户ID：{}", householdId);
        
        // 暂时返回空的影响分析，后续完善
        HouseholdDeleteImpactVO impact = new HouseholdDeleteImpactVO();
        impact.setHouseholdId(householdId);
        impact.setResidentRelationCount(0L);
        impact.setPropertyFeeCount(0L);
        impact.setSanitationFeeCount(0L);
        impact.setGasFeeCount(0L);
        impact.setUtilityFeeCount(0L);
        impact.setTotalRelatedCount(0L);
        impact.setSummary("无关联数据");
        
        log.info("房户删除影响检查完成，房户ID：{}，关联数据总数：0", householdId);
        return impact;
    }

    /**
     * 验证删除权限
     */
    private void validateDeletePermission(Long householdId, Long currentUserId) throws BusinessException {
        try {
            // 1. 获取房户信息
            Household household = this.getById(householdId);
            if (household == null) {
                throw new BusinessException("房户不存在");
            }

            // 2. 检查超级管理员权限
            Boolean isSuperAdmin = dataScopeFeign.isUserSuperAdmin(currentUserId);
            if (isSuperAdmin) {
                return;
            }

            // 3. 获取用户数据权限范围
            List<Long> authorizedCommunityIds = dataScopeFeign.getUserCommunityIds(currentUserId);
            if (!authorizedCommunityIds.contains(household.getCommunityId())) {
                throw new BusinessException("无权限删除该房户");
            }
        } catch (Exception e) {
            log.error("权限验证失败，房户ID：{}，用户ID：{}", householdId, currentUserId, e);
            throw new BusinessException("权限验证失败：" + e.getMessage());
        }
    }

    // ==================== Feign接口实现 ====================

    @Override
    @Cacheable(value = "household:feign:ids", key = "#householdIds.toString()", unless = "#result == null || #result.isEmpty()")
    public List<HouseholdInfoDTO> getHouseholdsByIdsForFeign(List<Long> householdIds) {
        log.info("Feign接口：根据房户ID集合批量获取房户信息，房户数量：{}", householdIds != null ? householdIds.size() : 0);
        
        try {
            if (householdIds == null || householdIds.isEmpty()) {
                log.info("房户ID列表为空，返回空列表");
                return new ArrayList<>();
            }
            
            // 查询房户信息
            LambdaQueryWrapper<Household> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(Household::getId, householdIds);
            queryWrapper.eq(Household::getDeleted, 0);
            
            List<Household> households = this.list(queryWrapper);
            log.debug("查询到房户信息：{}", households.size());
            
            // 转换为DTO
            List<HouseholdInfoDTO> householdDTOs = households.stream()
                    .map(household -> {
                        HouseholdInfoDTO dto = new HouseholdInfoDTO();
                        dto.setId(household.getId());
                        dto.setRoomNumber(household.getHouseholdCode());
                        dto.setRoomName(household.getRoomNumber());
                        dto.setArea(household.getArea() != null ? household.getArea().doubleValue() : null); // 关键字段：面积，转换为Double
                        dto.setUnitId(household.getUnitId());
                        dto.setBuildingId(household.getBuildingId());
                        dto.setCommunityId(household.getCommunityId());
                        dto.setStatus(household.getStatus());
                        dto.setCreateTime(household.getCreateTime());
                        dto.setUpdateTime(household.getUpdateTime());
                        return dto;
                    })
                    .collect(Collectors.toList());
            
            log.info("Feign接口：批量获取房户信息成功，房户数量：{}，DTO数量：{}", households.size(), householdDTOs.size());
            return householdDTOs;
            
        } catch (Exception e) {
            log.error("Feign接口：批量获取房户信息失败，房户IDs：{}", householdIds, e);
            return new ArrayList<>();
        }
    }

    // ==================== 房户详情Tab页方法实现 ====================

    @Override
    @Cacheable(value = "household:owners", key = "#householdId + ':' + #current + ':' + #size", unless = "#result == null || #result.getRecords().isEmpty()")
    public IPage<Object> getHouseholdOwners(Long householdId, Integer current, Integer size) throws Exception {
        log.info("获取房户业主列表，房户ID：{}，当前页：{}，每页大小：{}", householdId, current, size);
        
        try {
            // 创建分页对象
            Page<Object> page = new Page<>(current, size);
            
            // 查询房户业主关联表
            LambdaQueryWrapper<OwnerHousehold> ownerHouseholdQuery = new LambdaQueryWrapper<>();
            ownerHouseholdQuery.eq(OwnerHousehold::getHouseholdId, householdId);
            
            List<OwnerHousehold> ownerHouseholds = ownerHouseholdMapper.selectList(ownerHouseholdQuery);
            
            if (ownerHouseholds.isEmpty()) {
                log.info("房户ID：{} 没有关联的业主", householdId);
                return page;
            }
            
            // 获取业主ID列表
            List<Long> ownerIds = ownerHouseholds.stream()
                    .map(OwnerHousehold::getOwnerId)
                    .collect(Collectors.toList());
            
            // 查询业主信息
            LambdaQueryWrapper<Owner> ownerQuery = new LambdaQueryWrapper<>();
            ownerQuery.in(Owner::getId, ownerIds);
            ownerQuery.eq(Owner::getDeleted, 0);
            ownerQuery.orderByDesc(Owner::getCreateTime);
            
            // 设置分页
            Page<Owner> ownerPage = new Page<>(current, size);
            IPage<Owner> ownerIPage = ownerMapper.selectPage(ownerPage, ownerQuery);
            
            // 转换为Object类型的分页结果
            Page<Object> resultPage = new Page<>(current, size, ownerIPage.getTotal());
            resultPage.setRecords(new ArrayList<>(ownerIPage.getRecords()));
            
            log.info("获取房户业主列表成功，房户ID：{}，业主数量：{}", householdId, ownerIPage.getTotal());
            return resultPage;
            
        } catch (Exception e) {
            log.error("获取房户业主列表失败，房户ID：{}", householdId, e);
            throw new Exception("获取房户业主列表失败：" + e.getMessage());
        }
    }

    @Override
    @Cacheable(value = "household:family", key = "#householdId + ':' + #current + ':' + #size", unless = "#result == null || #result.getRecords().isEmpty()")
    public IPage<Object> getHouseholdFamilyMembers(Long householdId, Integer current, Integer size) throws Exception {
        log.info("获取房户家庭成员列表，房户ID：{}，当前页：{}，每页大小：{}", householdId, current, size);
        
        try {
            // 创建分页对象
            Page<Object> page = new Page<>(current, size);
            
            // 查询房户住户关联表，residentType=1或2（户主或家庭成员）
            LambdaQueryWrapper<ResidentHousehold> residentHouseholdQuery = new LambdaQueryWrapper<>();
            residentHouseholdQuery.eq(ResidentHousehold::getHouseholdId, householdId);
            residentHouseholdQuery.in(ResidentHousehold::getResidentType, 1, 2);
            residentHouseholdQuery.eq(ResidentHousehold::getDeleted, 0);
            
            List<ResidentHousehold> residentHouseholds = residentHouseholdMapper.selectList(residentHouseholdQuery);
            
            if (residentHouseholds.isEmpty()) {
                log.info("房户ID：{} 没有关联的家庭成员", householdId);
                return page;
            }
            
            // 获取住户ID列表
            List<Long> residentIds = residentHouseholds.stream()
                    .map(ResidentHousehold::getResidentId)
                    .collect(Collectors.toList());
            
            // 查询住户信息
            LambdaQueryWrapper<Resident> residentQuery = new LambdaQueryWrapper<>();
            residentQuery.in(Resident::getId, residentIds);
            residentQuery.eq(Resident::getDeleted, 0);
            residentQuery.orderByDesc(Resident::getCreateTime);
            
            // 设置分页
            Page<Resident> residentPage = new Page<>(current, size);
            IPage<Resident> residentIPage = residentMapper.selectPage(residentPage, residentQuery);
            
            // 转换为Object类型的分页结果
            Page<Object> resultPage = new Page<>(current, size, residentIPage.getTotal());
            resultPage.setRecords(new ArrayList<>(residentIPage.getRecords()));
            
            log.info("获取房户家庭成员列表成功，房户ID：{}，家庭成员数量：{}", householdId, residentIPage.getTotal());
            return resultPage;
            
        } catch (Exception e) {
            log.error("获取房户家庭成员列表失败，房户ID：{}", householdId, e);
            throw new Exception("获取房户家庭成员列表失败：" + e.getMessage());
        }
    }

    @Override
    @Cacheable(value = "household:tenants", key = "#householdId + ':' + #current + ':' + #size", unless = "#result == null || #result.getRecords().isEmpty()")
    public IPage<Object> getHouseholdTenants(Long householdId, Integer current, Integer size) throws Exception {
        log.info("获取房户租客列表，房户ID：{}，当前页：{}，每页大小：{}", householdId, current, size);
        
        try {
            // 创建分页对象
            Page<Object> page = new Page<>(current, size);
            
            // 查询房户住户关联表，residentType=3或4（租客或临时居住）
            LambdaQueryWrapper<ResidentHousehold> residentHouseholdQuery = new LambdaQueryWrapper<>();
            residentHouseholdQuery.eq(ResidentHousehold::getHouseholdId, householdId);
            residentHouseholdQuery.in(ResidentHousehold::getResidentType, 3, 4);
            residentHouseholdQuery.eq(ResidentHousehold::getDeleted, 0);
            
            List<ResidentHousehold> residentHouseholds = residentHouseholdMapper.selectList(residentHouseholdQuery);
            
            if (residentHouseholds.isEmpty()) {
                log.info("房户ID：{} 没有关联的租客", householdId);
                return page;
            }
            
            // 获取住户ID列表
            List<Long> residentIds = residentHouseholds.stream()
                    .map(ResidentHousehold::getResidentId)
                    .collect(Collectors.toList());
            
            // 查询住户信息
            LambdaQueryWrapper<Resident> residentQuery = new LambdaQueryWrapper<>();
            residentQuery.in(Resident::getId, residentIds);
            residentQuery.eq(Resident::getDeleted, 0);
            residentQuery.orderByDesc(Resident::getCreateTime);
            
            // 设置分页
            Page<Resident> residentPage = new Page<>(current, size);
            IPage<Resident> residentIPage = residentMapper.selectPage(residentPage, residentQuery);
            
            // 转换为Object类型的分页结果
            Page<Object> resultPage = new Page<>(current, size, residentIPage.getTotal());
            resultPage.setRecords(new ArrayList<>(residentIPage.getRecords()));
            
            log.info("获取房户租客列表成功，房户ID：{}，租客数量：{}", householdId, residentIPage.getTotal());
            return resultPage;
            
        } catch (Exception e) {
            log.error("获取房户租客列表失败，房户ID：{}", householdId, e);
            throw new Exception("获取房户租客列表失败：" + e.getMessage());
        }
    }

    @Override
    public List<Long> getOwnerUserIdsByHouseholdId(Long householdId) throws Exception {
        log.info("根据房户ID获取业主用户ID列表，房户ID：{}", householdId);
        
        try {
            // 查询房户业主关联表
            LambdaQueryWrapper<OwnerHousehold> ownerHouseholdQuery = new LambdaQueryWrapper<>();
            ownerHouseholdQuery.eq(OwnerHousehold::getHouseholdId, householdId);
            ownerHouseholdQuery.eq(OwnerHousehold::getStatus, 1);
            
            List<OwnerHousehold> ownerHouseholds = ownerHouseholdMapper.selectList(ownerHouseholdQuery);
            
            if (ownerHouseholds.isEmpty()) {
                log.info("房户ID：{} 没有关联的业主", householdId);
                return new ArrayList<>();
            }
            
            // 获取业主ID列表
            List<Long> ownerIds = ownerHouseholds.stream()
                    .map(OwnerHousehold::getOwnerId)
                    .collect(Collectors.toList());
            
            // 查询业主信息获取用户ID
            LambdaQueryWrapper<Owner> ownerQuery = new LambdaQueryWrapper<>();
            ownerQuery.in(Owner::getId, ownerIds);
            ownerQuery.eq(Owner::getDeleted, 0);
            ownerQuery.select(Owner::getUserId);
            
            List<Owner> owners = ownerMapper.selectList(ownerQuery);
            
            // 提取用户ID列表
            List<Long> userIds = owners.stream()
                    .map(Owner::getUserId)
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());
            
            log.info("根据房户ID获取业主用户ID列表成功，房户ID：{}，用户ID数量：{}", householdId, userIds.size());
            return userIds;
            
        } catch (Exception e) {
            log.error("根据房户ID获取业主用户ID列表失败，房户ID：{}", householdId, e);
            throw new Exception("根据房户ID获取业主用户ID列表失败：" + e.getMessage());
        }
    }

    @Override
    public List<Long> getResidentUserIdsByHouseholdId(Long householdId) throws Exception {
        log.info("根据房户ID获取住户用户ID列表，房户ID：{}", householdId);
        
        try {
            // 查询房户住户关联表
            LambdaQueryWrapper<ResidentHousehold> residentHouseholdQuery = new LambdaQueryWrapper<>();
            residentHouseholdQuery.eq(ResidentHousehold::getHouseholdId, householdId);
            residentHouseholdQuery.eq(ResidentHousehold::getDeleted, 0);
            
            List<ResidentHousehold> residentHouseholds = residentHouseholdMapper.selectList(residentHouseholdQuery);
            
            if (residentHouseholds.isEmpty()) {
                log.info("房户ID：{} 没有关联的住户", householdId);
                return new ArrayList<>();
            }
            
            // 获取住户ID列表
            List<Long> residentIds = residentHouseholds.stream()
                    .map(ResidentHousehold::getResidentId)
                    .collect(Collectors.toList());
            
            // 查询住户信息获取用户ID
            LambdaQueryWrapper<Resident> residentQuery = new LambdaQueryWrapper<>();
            residentQuery.in(Resident::getId, residentIds);
            residentQuery.eq(Resident::getDeleted, 0);
            residentQuery.select(Resident::getUserId);
            
            List<Resident> residents = residentMapper.selectList(residentQuery);
            
            // 提取用户ID列表
            List<Long> userIds = residents.stream()
                    .map(Resident::getUserId)
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());
            
            log.info("根据房户ID获取住户用户ID列表成功，房户ID：{}，用户ID数量：{}", householdId, userIds.size());
            return userIds;
            
        } catch (Exception e) {
            log.error("根据房户ID获取住户用户ID列表失败，房户ID：{}", householdId, e);
            throw new Exception("根据房户ID获取住户用户ID列表失败：" + e.getMessage());
        }
    }
}
